<?php

namespace App\Modules\Admin\Services\Water\Vip;

use App\Exceptions\Exception;
use App\Modules\Admin\Entities\Member\UsersModel;
use App\Modules\Admin\Entities\Vip\VipCardModel;
use App\Modules\Admin\Entities\Vip\VipLogModel;
use App\Modules\Admin\Entities\Vip\VipModel;

use App\Modules\Admin\Services\BaseService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Arr;

class VipService extends BaseService
{
    public function __construct(VipModel $model)
    {
        $this->model = $model;
    }
    public function lists(array $params) : array
    {
        $params['where_callback'] = function($query) use ($params){
            $request = request();
            // 按照名称进行搜索
            if (!empty($search = $request->input('search', ''))){
                $query->where('nickname', 'LIKE', '%' . trim($search) . '%');
            }
            // 置顶
            $set_top = $request->input('set_top', -1);
            if ($set_top > -1){
                $query->where('set_top', '=', $set_top);
            }

            if (!empty($search = $request->input('flag', ''))){
                $query->where('flag', 'LIKE', '%' . trim($search) . '%');
            }
        };

        return parent::lists($params); // TODO: Change the autogenerated stub
    }

    const int BUY = 0;//购买
    const int REDEEM = 1;//兑换
    /**
     * @return array
     */
    public function getVipList(): array
    {
        $list = VipModel::get();
        $data = [];
        foreach ($list as $item) {
            $data[] = [
                'id' => $item->id,
                'name' => $item->name,
                'image' => getPath($item->image),
                'content' => $item->content,
                'max_water' => $item->max_water/1000,//单位:ml
                'price' => $item->price/100,//单位:分
            ];
        }
        return $data;
    }

    /**
     * @param $userId
     * @return array
     */
    public function getUserVipInfo($userId): array
    {
        $info = UsersModel::find($userId);
        $vipId = Arr::get($info,'vip.id',0);
        if (!$vipId) {
            return [];
        }
        return [
            'name' => Arr::get($info,'vip.name',''),
            'image' => getPath(Arr::get($info,'vip.image','')),
            'content' => Arr::get($info,'vip.content',''),
            'max_water' => Arr::get($info,'vip.max_water',0)/1000,//单位:ml
            'end_time' => Arr::get($info,'vip_end_time',''),
        ];
    }

    /**
     * @param $userId
     * @param $number
     * @return true
     * @throws Exception
     */
    public function userVipRedeem($userId,$number): true
    {
        $info = VipCardModel::where('number',$number)->first();
        if (!$info) {
            error('卡号错误');
        }
        if($info->user_id) {
            error('卡号已使用');
        }
        $userInfo = User::find($userId);
        if($userInfo->vip_id) {
            error('您已经是会员，请在会员到期后兑换');
        }
        DB::beginTransaction();
        $startTime = date("Y-m-d H:i:s");
        $endTime = date("Y-m-d H:i:s",strtotime("+1 year"));
        $bool = $userInfo->update([
            'vip_id' => $info->vip_id,
            'vip_start_time' => $startTime,
            'vip_end_time' => $endTime,
        ]);
        if (!$bool) {
            DB::rollBack();
            error('兑换会员出错');
        }
        $bool = VipLogModel::create([
           'user_id' => $userInfo->id,
           'vip_id' => $info->vip_id,
           'type' => self::REDEEM,
           'number' => $number,
        ]);
        if (!$bool) {
            DB::rollBack();
            error('记录会员时间出错');
        }
        $bool = $info->update([
            'user_id' => $userInfo->id,
            'use_time' => date("Y-m-d H:i:s"),
        ]);
        if(!$bool) {
            DB::rollBack();
            error('激活会员卡出错');
        }
        DB::commit();
        return true;
    }
}
